<template>
  <div class="search-container">
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow"
    :search-text ='searchText' 
    />
    <!-- 搜索结果 -->   

     <!-- 联想介意 -->
    <search-suggestion v-else-if="searchText"
     :search-text ='searchText' 
     @search='onSearch'
     /> 
    <!-- 联想介意 -->

    <!-- 搜索历史记录 -->
    <search-history v-else
    :search-histories="searchHistories"
    />
    <!-- 搜索历史记录 -->
  </div>
</template>
 
 <script>
import searchHistory from "./components/search-history.vue";
import searchSuggestion from "./components/search-suggestion.vue";
import searchResult from "./components/search-result.vue";
export default {
  name: "SearchIndex",
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories:[]  //用来存储历史记录数据
    };
  },
  methods: {
    onSearch(val) {
    //   console.log(val); 
    // 更新文本款内容
    this.searchText = val

    //存储搜索记录
    //要求，不要在重复历史记录，最新得 排在最前面 
    const index = this.searchHistories.indexOf(val)
    if(index !== -1){
      this.searchHistories.splice(index,1)
    }
    //储存历史记录
    this.searchHistories.unshift(val) 
    //渲染搜索结果
      this.isResultShow = true
    },
    onCancel() {
      this.$router.back();
    },
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult,
  },
};
</script>
 
 <style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
 